import tkinter as tk
from tkinter import messagebox
import mysql.connector
import time

class TicketSellSysGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("TSS 车票销售终端")
        self.root.geometry("600x400")
        
        # 初始化变量
        self.destination = None
        self.ticket_type = None
        self.payment_method = None
        self.display_var = tk.StringVar()
        self.display_var.set("系统初始化完成，请输入目的地代码")
        
        # 数据库连接
        self.db_connection = self.connect_to_db()
        self.db_cursor = self.db_connection.cursor()
        
        # 创建界面组件
        self.create_widgets()
    
    def connect_to_db(self):
        """连接到MySQL数据库"""
        try:
            connection = mysql.connector.connect(
                host='localhost',       # 数据库主机
                user='root',            # 数据库用户名
                password='123456',    # 数据库密码
                database='tss'       # 使用的数据库名
            )
            if connection.is_connected():
                print("成功连接到数据库")
            return connection
        except mysql.connector.Error as err:
            print(f"数据库连接错误: {err}")
            return None
    
    def create_widgets(self):
        """创建所有的界面组件"""
        # 显示屏
        self.display_label = tk.Label(self.root, textvariable=self.display_var, width=50, height=3, bg="lightgray")
        self.display_label.pack(pady=10)
        
        # 目的地输入
        self.destination_label = tk.Label(self.root, text="请输入目的地代码:")
        self.destination_label.pack()
        self.destination_entry = tk.Entry(self.root)
        self.destination_entry.pack(pady=5)
        self.destination_button = tk.Button(self.root, text="确认目的地", command=self.input_destination)
        self.destination_button.pack(pady=5)
        
        # 车票选择
        self.ticket_label = tk.Label(self.root, text="请选择车票类型:")
        self.ticket_label.pack()
        self.ticket_options = ["单程票", "多次往返票", "坐席票"]
        self.ticket_type_var = tk.StringVar()
        self.ticket_type_var.set(self.ticket_options[0])  # 默认选第一个
        self.ticket_menu = tk.OptionMenu(self.root, self.ticket_type_var, *self.ticket_options)
        self.ticket_menu.pack(pady=5)
        self.ticket_button = tk.Button(self.root, text="选择车票类型", command=self.select_ticket_type)
        self.ticket_button.pack(pady=5)
        
        # 支付方式选择
        self.payment_label = tk.Label(self.root, text="请选择支付方式:")
        self.payment_label.pack()
        self.payment_options = ["MCard", "硬币", "纸币"]
        self.payment_type_var = tk.StringVar()
        self.payment_type_var.set(self.payment_options[0])  # 默认选第一个
        self.payment_menu = tk.OptionMenu(self.root, self.payment_type_var, *self.payment_options)
        self.payment_menu.pack(pady=5)
        self.payment_button = tk.Button(self.root, text="选择支付方式", command=self.select_payment)
        self.payment_button.pack(pady=5)
        
        # 确认支付和取消按钮
        self.confirm_button = tk.Button(self.root, text="确认支付", command=self.confirm_payment)
        self.confirm_button.pack(pady=10)
        self.cancel_button = tk.Button(self.root, text="取消购票", command=self.cancel_transaction)
        self.cancel_button.pack(pady=5)
    
    def input_destination(self):
        """输入目的地代码"""
        code = self.destination_entry.get()
        if code:
            self.destination = code
            self.display_var.set(f"已选择目的地: {code}")
        else:
            self.display_var.set("请输入有效的目的地代码!")
    
    def select_ticket_type(self):
        """选择车票类型"""
        self.ticket_type = self.ticket_type_var.get()
        self.display_var.set(f"已选择车票类型: {self.ticket_type}")
    
    def select_payment(self):
        """选择支付方式"""
        self.payment_method = self.payment_type_var.get()
        self.display_var.set(f"已选择付款方式: {self.payment_method}")
    
    def confirm_payment(self):
        """确认支付并打印车票"""
        if not self.destination or not self.ticket_type or not self.payment_method:
            messagebox.showerror("错误", "请完整选择目的地、车票类型和支付方式！")
        else:
            self.display_var.set(f"支付成功！\n目的地: {self.destination}\n车票类型: {self.ticket_type}\n付款方式: {self.payment_method}\n正在打印车票...")
            self.save_transaction_to_db()
            self.print_ticket()
    
    def save_transaction_to_db(self):
        """将购票信息保存到数据库"""
        try:
            query = "INSERT INTO transactions (destination, ticket_type, payment_method) VALUES (%s, %s, %s)"
            values = (self.destination, self.ticket_type, self.payment_method)
            self.db_cursor.execute(query, values)
            self.db_connection.commit()
            print("交易已保存到数据库")
        except mysql.connector.Error as err:
            print(f"数据库插入错误: {err}")
    
    def print_ticket(self):
        """模拟打印车票"""
        messagebox.showinfo("车票打印", f"*** 车票信息 ***\n目的地: {self.destination}\n车票类型: {self.ticket_type}\n付款方式: {self.payment_method}\n===== 车票打印完成 =====")
    
    def cancel_transaction(self):
        """取消购票过程"""
        self.display_var.set("购票已取消，系统恢复初始状态。")
        self.reset_system()
    
    def reset_system(self):
        """重置系统状态"""
        self.destination = None
        self.ticket_type = None
        self.payment_method = None
        self.display_var.set("系统初始化完成，请输入目的地代码")

# 主程序
if __name__ == "__main__":
    root = tk.Tk()
    tss_gui = TicketSellSysGUI(root)
    root.mainloop()
